package mo.org.cm309.shoppingcart.servlet.test;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mo.org.cm309.shoppingcart.entity.Product;
import mo.org.cm309.shoppingcart.service.ProductService;
import mo.org.cm309.shoppingcart.utility.CommonUtility;

public class ProductStockAdjustServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try{
			//Test URL : http://localhost:8083/CM309_TEAM_B_3C_Shopping_Cart/productStockAdjustServlet?productId=1
			//BEFORE TESTING, PLEASE EXECUTE THE SQLSCRIPT
			String id = req.getParameter("productId");
			long pid  = CommonUtility.getLongByString(id);
			
			//GET PRODUCT SERVICE
			ProductService productService = new ProductService();
			//GET PRODUCT BY ID
			Product product = productService.getProductById(pid);
			//ADD PRODUCT STOCK
			product = productService.setStock(product, 1);
			//UPDATE NEW PRODUCT TO DATABASE
			productService.update(product);
			
			//IF ACTION SUCCESSFUL, RETURN A SUCCESS PAGE
			PrintWriter writer = resp.getWriter();
			writer.print("<html>");
			writer.print("Update product : " + id + " stock successful!");
			writer.print("</html>");
		}catch(Exception e){
			e.printStackTrace();
			//IF FOUND EXCEPTION, RETURN A FAILURE PAGE
			PrintWriter writer = resp.getWriter();
			writer.print("<html>");
			writer.print("ERROR! Update product stock failure!");
			writer.print("</html>");
		}
		
	}
}
